{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "\n",
    "插入排序\n",
    "\n",
    "    \n",
    "    \n",
    "    1、从第一个元素开始，该元素可以认为已经被排序\n",
    "    2、取出下一个元素，在已经排序的元素序列中从后向前扫描\n",
    "    3、如果被扫描的元素（已排序）大于新元素，将该元素后移一位\n",
    "    4、重复步骤3，直到找到已排序的元素小于或者等于新元素的位置\n",
    "    5、将新元素插入到该位置后\n",
    "    6、重复步骤2~5\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def insert_sort(nums):\n",
    "    n = len(nums)\n",
    "    \n",
    "    for i in range(1,n):\n",
    "        tmp = nums[i]\n",
    "        k = i\n",
    "        while k >= 1 and nums[k-1] > tmp:\n",
    "            nums[k] = nums[k-1]   # 找合适的位置，给tmp 腾地方。\n",
    "            k -= 1\n",
    "        nums[k] = tmp\n",
    "    return nums"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 5, 6, 7, 8, 9]"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nums = [1,4,8,3,7,2,5,9,6]\n",
    "insert_sort(nums)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "insert_sort  0.006411900001694448 ms\n"
     ]
    }
   ],
   "source": [
    "import timeit\n",
    "print(\"insert_sort \",timeit.timeit(\"insert_sort([1,4,8,3,7,2,5,9,6])\", setup=\"from __main__ import insert_sort\", number=1000), \"ms\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
